package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


/**
 * @author hea7en
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传递过来的密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void saveOrUpdateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        // 修改
        if (employeeDTO.getId()!=null) {
            // 前端页面回填数据已经调用过了getById
//             employee = employeeMapper.getById(employeeDTO.getId());
            BeanUtils.copyProperties(employeeDTO, employee);
//            employee.setUpdateTime(LocalDateTime.now());
//            employee.setUpdateUser(BaseContext.getCurrentId());
            employeeMapper.update(employee);
        }
        // 新增
        else {
            BeanUtils.copyProperties(employeeDTO, employee);
            employee.setStatus(StatusConstant.ENABLE);
//            employee.setCreateTime(LocalDateTime.now());
//            employee.setUpdateTime(LocalDateTime.now());
            employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

            // 从线程局部变量中获取当前登录用户的id
            employee.setCreateUser(BaseContext.getCurrentId());
            employeeMapper.save(employee);
        }
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO pageQueryDTO) {
        // 开启分页查询，底层会将分页信息存储到ThreadLocal中
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        // 执行查询
        Page<Employee> page = employeeMapper.pageQuery(pageQueryDTO);
        // 返回结果
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        // 实体类添加了@Builder注解，可以使用链式编程创建对象
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }

    @Override
    public Employee getEmployeeById(Long id) {
        Employee employee = employeeMapper.getById(id);
        // 密码安全性处理
        employee.setPassword("******");
        return employee;
    }

    @Override
    public Result editPassword(PasswordEditDTO passwordEditDTO) {
        // 获取当前登录用户的id
        Long empId = BaseContext.getCurrentId();
        Employee employee = employeeMapper.getById(empId);
        // 对前端传过来的密码加密用于比对
        String password = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        // 校验原始密码是否正确
        if (!password.equals(employee.getPassword())) {
            return Result.error("原始密码输入错误！");
        }
        // 修改新密码
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        employee.setPassword(newPassword);
        employeeMapper.update(employee);
        return Result.success();
    }

}
